/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-04 10:32:03
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-04 16:00:03
 * @FilePath: /110/51/tcp_echo_server/TcpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>
#include "ThreePool.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEM_REEOR,
    USAGE_ERROR
};

const static int defaultsockfd = -1;
const static int gbacklog = 16; // 服务器端套接字监听队列的长度  不能太大和太小

class TcpServer; // 前向声明

class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s) : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self; // 获取TcpServer对象指针
};

using task_t = std::function<void()>;

class TcpServer
{
public:
    TcpServer(int port) : _port(port), _listensock(defaultsockfd), _isrunning(false)
    {
    }
    ~TcpServer()
    {
        if (_listensock > defaultsockfd)
            ::close(_listensock); // 关闭监听套接字
    }
    void InitServer()
    {
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0); // 创建TCP套接字
        if (_listensock < 0)
        {
            LOG(FATAL, "socket error");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success,sockfd is : %d\n", _listensock);

        // 填充服务器端套接字地址 sockaddr_in
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);

        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local)); // 绑定服务器端套接字地址
        if (n < 0)
        {
            LOG(FATAL, "bind error");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success,sockfd is : %d\n", _listensock);

        // 3. tcp是面向连接的，所以通信之前，必须先建立连接。服务器是被连接的
        //    tcpserver 启动，未来首先要一直等待客户的连接到来
        n = ::listen(_listensock, gbacklog); // 监听客户端连接
        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEM_REEOR);
        }
        LOG(DEBUG, "listen success,sockfd is : %d\n", _listensock);
    }

    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link,info %s:%d, fd : %d\n", client.IP().c_str(), client.Port(), sockfd); // 获取客户端信息

        std::string clientaddr = "[" + client.IP() + ":" + std::to_string(client.Port()) + "]# "; // 获取客户端信息
        while (1)
        {
            char inbuffer[1024];                                        // 读取客户端发送的数据
            ssize_t n = ::read(sockfd, inbuffer, sizeof(inbuffer) - 1); // 读取客户端发送的数据
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << clientaddr << inbuffer << std::endl; // 输出客户端发送的数据
                std::string echo_string = "[server echo]#";
                echo_string += inbuffer;

                ::write(sockfd, echo_string.c_str(), echo_string.size()); // 回显客户端发送的数据
            }
            else if (n == 0)
            {
                // client 退出&关闭连接了
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n", clientaddr.c_str());
                break;
            }
        }
        ::close(sockfd); // 关闭套接字 否则文件描述符泄漏
    }

    static void *HandlerSock(void *args) // 线程处理函数
    {
        pthread_detach(pthread_self()); // 设置线程分离
        ThreadData *td = (ThreadData *)args;
        td->self->Service(td->sockfd, td->clientaddr); // 调用TcpServer的Service函数

        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensock, (struct sockaddr *)&peer, &len); // 链接
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }

            // // Version 0
            // Service(sockfd, InetAddr(peer));

            // // Version 1 采用多进程
            // pid_t id = fork();
            // if (id == 0)
            // {
            //     // 子进程
            //     ::close(_listensock); // 关闭监听套接字
            //     if (fork() > 0)
            //         exit(0);                     // 子进程再fork一个子进程，父进程退出，子进程继续处理客户端请求
            //     Service(sockfd, InetAddr(peer)); // 子处理客户端请求    ----- 孤儿进程 -------系统领养
            //     exit(0);
            // }

            // 父进程
            //::close(sockfd);
            // waitpid(id, nullptr, 0);

            // Version 2 采用多线程
            pthread_t t;
            ThreadData *td = new ThreadData(sockfd, InetAddr(peer), this); // 创建线程数据
            pthread_create(&t, nullptr, HandlerSock, td);                  // 创建线程

            // // Version 3 采用线程池
            // task_t t = std::bind(&TcpServer::Service, this, sockfd, InetAddr(peer)); // 将任务封装成函数对象
            // ThreadPool<task_t>::GetInstance()->Enqueue(t);                           // 将任务加入线程池
        }
        _isrunning = false;
    }

private:
    uint16_t _port;  // 服务器端口
    int _listensock; // 服务器端套接字
    bool _isrunning; // 服务器是否在运行
};